import utils from '../core/utils';
import logger from '../core/logger';
import current from '../core/current';
import { clientBase } from './core/clientBase';
import userInfo from '../models/user/userInfo';
import { smsModel } from '../models/user/smsModel';
import { countryItem } from '../models/user/countryItem';
import { loginCallback } from '../models/user/loginCallback';
import axios, { AxiosError, AxiosResponse } from '@ohos/axios';

class loginClient extends  clientBase {
  getCountry(): Promise<countryItem[] | string> {
    return new Promise(async (resolve) => {
      try {
        let url = await this.createGetParam('https://passport.bilibili.com/x/passport-login/country', true);
        axios.get<string, AxiosResponse<string>, null>(url)
          .then((response: AxiosResponse) => {
            if (response.status == 200) {
              if (this.isSuccess(response.data)) {
                let ret: Array<countryItem> = response.data.data.list;
                resolve(ret);
              } else {
                let msg = this.repMessage(response.data);
                resolve(msg);
              }
            } else
              resolve(response.statusText);
          }).catch((err: AxiosError) => {
          logger.error(err);
          resolve(this.errMessage(err));
        });
      } catch (err) {
        logger.error(err);
        resolve('');
      }
    });
  }

  getInfo(mid: string): Promise<userInfo | string> {
    return new Promise(async (resolve) => {
      try {
        let url = await this.createGetParam(`https://app.bilibili.com/x/v2/space?vmid=${mid}`, false);
        axios.get<string, AxiosResponse<string>, null>(url)
          .then((response: AxiosResponse) => {
            if (response.status == 200) {
              if (this.isSuccess(response.data)) {
                let ret: userInfo = response.data.data;
                resolve(ret);
              } else {
                let msg = this.repMessage(response.data);
                resolve(msg);
              }
            } else {
              let msg = this.repMessage(response.data);
              resolve(msg);
            }
          }).catch((err: AxiosError) => {
          logger.error(err);
          resolve(this.errMessage(err));
        });
      } catch (err) {
        logger.error(err);
        resolve('');
      }
    });
  }

  sendSms(cid: string, phone: string, sid: string, recaptcha_token: string, secCode: string, validate: string, challenge: string): Promise<smsModel | string> {
    return new Promise(async (resolve) => {
      try {
        let data = `&channel=bili&cid=${cid}&tel=${phone}&login_session_id=${sid}&statistics=${encodeURIComponent('{"appId":1,"platform":3,"version":"7.27.0","abtest":""}')}&buvid=${current.instance.buvId}&local_id=${current.instance.buvId}`;
        if (!utils.isEmpty(recaptcha_token)) {
          data += `&gee_seccode=${encodeURIComponent(secCode)}&gee_validate=${encodeURIComponent(validate)}&gee_challenge=${encodeURIComponent(challenge)}&recaptcha_token=${encodeURIComponent(recaptcha_token)}`;
        }
        let param = await this.createPostParam(data);
        axios.post<string, AxiosResponse<string>, any>('https://passport.bilibili.com/x/passport-login/sms/send', param)
          .then((response: AxiosResponse) => {
            if (response.status == 200) {
              if (this.isSuccess(response.data)) {
                let url = response.data.data.recaptcha_url;
                let key = response.data.data.captcha_key;
                resolve(new smsModel(key, url));
              } else {
                let msg = this.repMessage(response.data);
                resolve(msg);
              }
            } else
              resolve(response.statusText);
          }).catch((err: AxiosError) => {
          logger.error(err);
          resolve(this.errMessage(err));
        });
      } catch (err) {
        logger.error(err);
        resolve('');
      }
    });
  }

  login(cid: string, phone: string, sid: string, captchaKey: string, code: string): Promise<loginCallback | string> {
    return new Promise(async (resolve) => {
      try {
        let data = await this.createPostParam(`cid=${cid}&tel=${phone}&login_session_id=${sid}&captcha_key=${captchaKey}&code=${code}`);
        axios.post<string, AxiosResponse<string>, any>('https://passport.bilibili.com/x/passport-login/login/sms', data)
          .then((response: AxiosResponse) => {
            if (response.status == 200) {
              if (this.isSuccess(response.data)) {
                let mid = response.data.data.token_info.mid.toString();
                let expires_in = response.data.data.token_info.expires_in.toString();
                let accessKey = response.data.data.token_info.access_token.toString();
                let refresh_token = response.data.data.token_info.refresh_token.toString();
                let cookies, csrf;
                response.data.data.cookie_info.cookies.forEach((item) => {
                  if (item.name.includes('bili_jct'))
                    csrf = item.value;
                  cookies += `${item.name}=${item.value};`
                });
                let model = new loginCallback(mid, csrf, expires_in, accessKey, refresh_token, cookies);
                logger.info(`login info:${JSON.stringify(model)}`);
                resolve(model);
              } else {
                let msg = this.repMessage(response.data);
                resolve(msg);
              }
            } else
              resolve(response.statusText);
          }).catch((err: AxiosError) => {
          logger.error(err);
          resolve(this.errMessage(err));
        });
      } catch (err) {
        logger.error(err);
        resolve('');
      }
    });
  }
}
export default new loginClient();